package tr.edu.yildiz.ce.dap.appagent.process;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import java.util.Set;

import tr.edu.yildiz.ce.dap.appagent.manager.AgentProcessManager;
import tr.edu.yildiz.ce.dap.appagent.process.base.AbstractProcess;
import tr.edu.yildiz.ce.dap.appagent.service.infra.NetworkManager;
import tr.edu.yildiz.ce.dap.appagent.util.AgentProperties;

public class ListenerProcess extends AbstractProcess implements Runnable {

	Integer port;
	AgentMessageReceivedCallBack agentMessageReceivedCallBack;
	
	public ListenerProcess(AgentProcessManager processManager,Integer port) {
		super(processManager);
		this.port = port;
	}
	
	class AgentMessageReceivedCallBack implements NetworkManager.MessageReceivedCallBack {

		boolean stop = false;
		
		@Override
		public void onMessageReceived(String incomingMessage,
				SelectionKey sKey) {
			getProcessManager().createProxyCommand(incomingMessage,sKey);
		}

		@Override
		public void onConnectionFailed() {
			getProcessManager().setNeedsRegistration(true);
		}

		@Override
		public void stop() {
			stop = true;
		}
		
		@Override
		public boolean isStop() {
			return stop;
		}
		
	}

	@Override
	public void run(){
		NetworkManager networkManager = (NetworkManager) getProcessManager().getService(NetworkManager.class.getName());
		agentMessageReceivedCallBack = new AgentMessageReceivedCallBack();
		networkManager.listen(agentMessageReceivedCallBack, port);
	}
	
	@Override
	public void stop() {
		super.stop();
		agentMessageReceivedCallBack.stop();
	}
	
}
